package com.small.nine.wxmp.service.impl;

import cn.hutool.http.HttpUtil;
import com.small.nine.wxmp.common.constant.WxConstant;
import com.small.nine.wxmp.domain.bean.wx.WxInMsgBean;
import com.small.nine.wxmp.domain.bean.wx.kf.msg.WxKfImageMsgBean;
import com.small.nine.wxmp.domain.bean.wx.kf.msg.WxKfNewsMsgBean;
import com.small.nine.wxmp.domain.bean.wx.kf.msg.WxKfTextMsgBean;
import com.small.nine.wxmp.service.WxAsyncService;
import com.small.nine.wxmp.service.WxService;
import com.small.nine.wxmp.utils.wx.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author sheng_zs@126.com
 * @date 2021-08-06 17:40
 */
@Slf4j
@Service
public class WxAsyncServiceImpl implements WxAsyncService {
    @Resource
    private WxService wxService;

    @Async
    @Override
    public void kfSend(WxInMsgBean msgBean) {
        String msg = "";

        log.info("微信+++++异步处理+++++ one +++++ WxInMsgBean: {}", msgBean.toString());
        switch (msgBean.getMsgType()) {
            case WxConstant.MSG_TYPE_TEXT:
                // 处理 文本信息
                msg = JsonUtils.writeValueAsString(WxKfTextMsgBean.getInstance(msgBean.getFromUserName(), msgBean.getContent()));
                break;
            case WxConstant.MSG_TYPE_IMAGE:
                // 处理图片信息
                msg = JsonUtils.writeValueAsString(WxKfImageMsgBean.getInstance(msgBean.getFromUserName(), msgBean.getMediaId()));
                break;
            case WxConstant.MSG_TYPE_EVENT:
                // 处理事件
                switch (msgBean.getEvent()) {
                    case WxConstant.EVENT_TYPE_SUBSCRIBE:
                        // 用户关注公众号
                        msg = JsonUtils.writeValueAsString(WxKfNewsMsgBean.getInstance(msgBean.getFromUserName(), "http://www.baidu.com", "http://mmbiz.qpic.cn/mmbiz_jpg/8IpUia88gYWiaj07aFP5jcHH5gDlicXhlgNwS2gxfEbC1T4NLGAr9qowOPLHIXBHFhewUxaogqcDMHgcmnZyt5MibA/0", "title", "说明"));
                        break;
                    case WxConstant.EVENT_TYPE_UNSUBSCRIBE:
                        // 用户取消关注
                        // 加入黑名单、删除数据库等操作
                        break;
                    default:
                        msg = JsonUtils.writeValueAsString(WxKfTextMsgBean.getInstance(msgBean.getFromUserName(), "事件推送：" + msgBean.getEvent()));
                        break;
                }
                break;
            default:
                msg = JsonUtils.writeValueAsString(WxKfTextMsgBean.getInstance(msgBean.getFromUserName(), "请发送图片或者文字内容！"));
                break;
        }
        log.info("回复信息 msg: {}", msg);
        // 调用接口
        final String url = String.format(WxConstant.URL_CUSTOM_SEND_POST, wxService.getAccessToken());
        String post = HttpUtil.post(url, msg);
        log.info("微信+++++异步处理+++++ end +++++ 发送结果：{}", post);
    }
}
